using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using MonoCash.ObjectModel;
namespace MonoCash
{
    class Settings
    {
        Configuration configManager = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
        public Settings()
        {
            //Read appconfig.
            foreach (String key in configManager.AppSettings.Settings.AllKeys)
            {
                this.GetType().GetProperty(key).SetValue(this,configManager.AppSettings.Settings[key].Value,null);
	        }

            if (XmlBackendFile == null)
            {
                XmlBackendFile = configManager.FilePath.Replace("MonoCash.exe.config", "MonoCash.xml");
            }

        }

        public void SaveSettings()
        {
            foreach (System.Reflection.PropertyInfo property in GetType().GetProperties())
            {
                if (property.PropertyType.Equals(Type.GetType("System.String"))) 
                {
                    SaveProperty(property.Name, property.GetValue(this, null).ToString());
                }
            }
            configManager.Save();
            
        }

        private void SaveProperty(string name, string value)
        {
            
            
            bool hasKey = false;
            foreach (String key in configManager.AppSettings.Settings.AllKeys)
            {
                if (key == name)
                {
                    hasKey = true;
                }
            }
            if (!hasKey)
            {
                configManager.AppSettings.Settings.Add(name, value);
            }
            else
            {
                configManager.AppSettings.Settings[name].Value = value;
            }
        }

        private string backendType = "MonoCash.Data.XmlBackend";
        public string DataStorageType
        {
            get { return backendType; }
            set { backendType = value;  }
        }
	

        private Data.DataBackend backend;
        public Data.DataBackend Data
        {
            get { return backend; }
            set { backend =value; }
        }

        private string xmlBackendFile;
        public string XmlBackendFile
        {
            get { return xmlBackendFile; }
            set { xmlBackendFile = value;  }
        }

        private string priceEngineType = "MonoCash.Data.YahooQuotes";
        public string PriceEngineType
        {
            get { return priceEngineType; }
            set { priceEngineType = value; }
        }
        private Data.QuoteEngine priceEngine;
        public Data.QuoteEngine PriceEngine
        {
            get { return priceEngine; }
            set { priceEngine = value; }
        }

        private string defaultCurrencyID  = "-1";

        public string DefaultCurrencyID
        {
            get { return defaultCurrencyID; }
            set { defaultCurrencyID = value; }
        }
        private string defaultSecurityID = "-1";

        public string DefaultSecurityID
        {
            get { return defaultSecurityID; }
            set { defaultSecurityID = value; }
        }
        private string unbalancedTransactionsAccountID = "-1";
        public string UnbalancedTransactionsAccountID
        {
            get { return unbalancedTransactionsAccountID; }
            set { unbalancedTransactionsAccountID = value; }
        }
        private string defaultTransactionDetailType = "-1";

        public string DefaultTransactionDetailType
        {
            get { return defaultTransactionDetailType ; }
            set { defaultTransactionDetailType = value; }
        }
	

        public void InstallDefaults(string currencySymbol, string currencyDescription)
        {
            string[] at = {"Checking", "Savings", "Investment", "Asset", "Equity", "Expense", "Income", "Loan", "Credit Card", "Liability" };
            AccountType equityAccountType = new AccountType();
            foreach (string accountType in at)
            {
                AccountType a = new AccountType();
                a.Name = accountType;
                if (accountType == "Equity")
                {
                    equityAccountType = a;
                }
            }

            AccountType GroupAccountType = new AccountType();
            GroupAccountType.Name = "AccountGroup";

            Dictionary<string, string[]> accounts = new Dictionary<string,string[]>();
            accounts.Add("Assets", new string[0]);
            accounts.Add("Liabilities", new string[0]);
            accounts.Add("Income", new string[0]);
            accounts.Add("Expense", new string[0]);
            accounts.Add("Equity", new string[] {"Retained Earnings", "UnBalanced Transactions" });
            foreach (string cat in accounts.Keys)
            {
                AccountingCategory a = new AccountingCategory();
                a.Name = cat;
                a.ReverseSignForDisplay = (a.Name == "Liabilities" || a.Name == "Income");
                a.IsBalanceSheetCategory = !(a.Name == "Income" || a.Name == "Expense");

                Account act = new Account();
                act.Name = cat;
                act.AccountType = GroupAccountType;
                act.AccountingCategory = a;

                foreach (string subAct in accounts[cat])
                {
                    Account sub = new Account();
                    sub.ParentAccount = act;
                    sub.Name = subAct;
                    sub.AccountingCategory = a;
                    sub.AllowTransactions = true;
                    sub.AccountType = equityAccountType;
                }
            }

            string[] tdTypes = {"Deposit", "Withdrawal", "Buy", "Sell", "Dividend", "Interest"};
            foreach (string type in tdTypes)
            {
                TransactionDetailType tdt = new TransactionDetailType();
                tdt.Name = type;
                tdt.IncludeInCostBasis = !(tdt.Name == "Dividend" || tdt.Name == "Interest");
            }

            Currency c = new Currency();
            c.Symbol = currencySymbol;
            c.Description = currencyDescription;

            CurrencyConversion.Add(c, c, DateTime.MinValue, 1);

            Security s = new Security();      
            s.Symbol = "CASH";
            s.Description = "Cash Transactions";
            s.Currency = c;
            s.DownloadPrices = false;
            s.Prices.Add(DateTime.MinValue, 1);

        }
        public void InstallDefaults()
        {
            InstallDefaults("USD", "United States Dollars");
        }
    }
}
